<template>
  <div>
    <!-- 面包屑导区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- :to="{ path: '/homePage' }" -->
      <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-button type="primary">添加角色</el-button>

      <el-table :data="roleList" :border="true" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 数据格式美化标签 -->
            <!-- <pre>{{ scope.row }}</pre> -->

            <el-row
              :class="['bdBottom', 'rowCenter', idx === 0 ? 'bdTop' : '']"
              v-for="(item, idx) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag>{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[idx2 === 0 ? '' : 'bdTop', 'rowCenter']"
                  v-for="(item2, idx2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="8">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      closable
                      @close="deleteRightByRoleId(scope.row, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>

        <el-table-column prop="roleName" label="角色名称"></el-table-column>

        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>

        <el-table-column label="操作" width="800">
          <template slot-scope="scope">
            <!-- @click="getUserDetail(scope.row.id)" -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="getUserDetailV2(scope.row)"
              >编辑</el-button
            >

            <el-button type="danger" icon="el-icon-delete" size="small"
              >删除</el-button
            >

            <el-button
              type="warning"
              icon="el-icon-star-off"
              size="small"
              @click="openSetRightsDialog(scope.row,rightIdLeaf)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 关闭对话框，清空选中节点数组，此方法可以省略，在打开对话框之前先清空 -->
    <!-- @closed = "closeSetRightsDialog" -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="30%"
    
    >
      <!-- <span>这是一段信息</span> -->

      <el-tree
        ref="rightsTreeRef"
        :data="rightList"
        :props="rightProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="rightIdLeaf"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
    
    <script>
export default {
  data() {
    //数据区
    return {
      roleList: [],
      setRightsDialogVisible: false,
      rightProps: {
        children: "children",
        label: "authName",
      },
      rightList: [],
      rightIdLeaf: [],
      rightIdLeafV2: [104,145],
      emptyArr: [],
      currentRoleId: ''
    };
  },

  //方法区
  methods: {
    
    // 递归得到树形结构需要勾选的子节点
    getRightLeafIdList(node,arr){
      // 如果不包含子节点，证明他是一个三级节点
      if(!node.children) {
        arr.push(node.id) ;
        return;
      }
      node.children.forEach(element => {
        this.getRightLeafIdList(element,arr)
      });

    },

    //
    closeSetRightsDialog(){
      this.rightIdLeaf = []
    },
    // 打开分配权限对话框 
    async openSetRightsDialog(row,rightIdLeaf) {
      // 1.得到权限树形结构数据
      const { data: resData } = await this.$http.get("rights/tree");
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      this.rightList = resData.data;
      
      // 2.打开对话框前先清空选中节点数组，然后再进行赋值渲染
      this.rightIdLeaf.length = 0;
      this.getRightLeafIdList(row,rightIdLeaf);
      //console.log('rightIdLeaf is ' + this.rightIdLeaf)
      
      // 3.缓存当前角色id
      this.currentRoleId = row.id
      
      this.setRightsDialogVisible = true;
    },

    // 点击确定分配权限
    async setRights() {

      // ref引用可以调用组件里面的方法
      const checkedKeys = this.$refs.rightsTreeRef.getCheckedKeys();
      const HalfCheckedKeys = this.$refs.rightsTreeRef.getHalfCheckedKeys();
      const allkeysStr = checkedKeys + ',' + HalfCheckedKeys
      //console.log('allkeys is ' + allkeysStr)
      
      const allkeys = [
      ...this.$refs.rightsTreeRef.getCheckedKeys(),
      ...this.$refs.rightsTreeRef.getHalfCheckedKeys() ]
      const allkeysStr2 = allkeys.join(',')
      console.log('allkeysStr2 is ' + allkeysStr2)

      const { data: resData } = await this.$http.post(`roles/${this.currentRoleId}/rights`,{rids: allkeysStr2})
      if (resData.meta.status !== 200){
        //console.log('resData is ' + resData)
        return this.$message.error(resData.meta.msg);
       }
      
      // 主要是 刷新 角色相关的权限树形结构数据 以 
      this.getRoleList(); 

      this.setRightsDialogVisible = false;
    },

    // 角色列表
    async getRoleList() {
      const { data: resData } = await this.$http.get("roles");
      if (resData.meta.status !== 200)
        return this.$message.error(resData.meta.msg);
      this.roleList = resData.data;
    },

    // 根据角色id删除对应权限
    async deleteRightByRoleId(row, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色的权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      console.log("confirmResult is " + confirmResult);
      if (confirmResult === "cancel") return this.$message.info("已取消删除");

      // 返回的data, 是当前角色下最新的权限数据
      const { data: resData } = await this.$http.delete(
        `roles/${row.id}/rights/${rightId}`
      );
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      //this.getRoleList();
      //重新调用列表接口会刷新整个页面，使expand列关闭。 接口返回的data, 是当前角色下最新的权限数据,因此重新赋值
      row.children = resData.data;
    },
  },

  //钩子函数
  created() {
    this.getRoleList();
  },
};
</script>
    
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdTop {
  // margin-top: 15px;
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}

.rowCenter {
  display: flex;
  align-items: center;
}
</style>